package com.yuxi;

import java.util.LinkedList;

/**
 * 生产者和消费者问题
 * <p>
 * Created by yuxi on 17/2/2.
 */
public class ConsProd {
    private static LinkedList buffer = new LinkedList();
    private static int size = 10;

    public static void main(String[] args) {
        Consumer consumer = new Consumer();
        Producer produer = new Producer();
        while(true) {
            new Thread(produer).start();
            new Thread(produer).start();
            new Thread(consumer).start();
        }

    }

    static class Producer implements Runnable {
        public void run() {
            synchronized (this) {
                if (buffer.size() == size) {
                    System.out.println("生产过剩了。。。。。");
                    this.notify();
                } else {
                    buffer.add("something");
                    System.out.println("生产者生产了.....");
                }
            }
        }
    }

    static class Consumer implements Runnable {

        public void run() {
            synchronized (this) {
                if (buffer.isEmpty() || buffer.size() == 0) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    Object o = buffer.removeFirst();
                    System.out.println("消费者消费了...." + o);
                }
            }
        }
    }
}
